//
//  MyStoreObserver.m
//  SignatureN
//
//  Created by fanshao on 09-9-1.
//  Copyright 2009 Sensky. All rights reserved.
//

#import "MyStoreObserver.h"
#import<UIKit/UIKit.h>
#import<UIKit/UIAlert.h>
#import "JSON.h"
#import "ASIFormDataRequest.h"

@implementation MyStoreObserver


- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
	NSLog(@"paymetnQueue------");
	for (SKPaymentTransaction* transaction in transactions)
	{
		switch (transaction.transactionState)
		{
			case SKPaymentTransactionStatePurchased:
				NSLog(@"Complete Transaction");
				[self completeTransaction:transaction];
				break;
			case SKPaymentTransactionStateFailed:
                NSLog(@"付费失败");
				[self failedTransaction:transaction];
				break;
			case SKPaymentTransactionStateRestored:
                NSLog(@"已经付费了");
				break;
			default:
				break;
		}
	}
}

-(void) PurchasedTransaction: (SKPaymentTransaction *)transaction{
    NSLog(@"PurchasedTransaction");
	NSArray *transactions =[[NSArray alloc] initWithObjects:transaction, nil];
	[self paymentQueue:[SKPaymentQueue defaultQueue] updatedTransactions:transactions];
	[transactions release];
}
				
- (void) completeTransaction: (SKPaymentTransaction *)transaction
{
    NSString* jsonObjectString = [self encode:(uint8_t *)transaction.transactionReceipt.bytes
                                       length:transaction.transactionReceipt.length];
//    NSString* varStr = [[NSString alloc] initWithFormat:
//                        @"your_url?receipt=%@",
//                        jsonObjectString];
//    VMRequest* request = [[VMRequest alloc] initWithVariableStr:varStr
//                                                    requestType:PURCHASED_IAP_PRODUCT
//                                                       delegate:self];
//    [[VMRequestQueue sharedQueue] addRequest:request
//                                     toQueue:[VMRequestQueue sharedQueue].requestSetInfoQueue];
//    [mIAPRequestDict setObject:request forKey:transaction.transactionIdentifier];
//    [varStr release];
//    [request release];
    
    
	/*NSString *transactionReceipt = [[NSString alloc] initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding];
	[[NSNotificationCenter defaultCenter]  postNotificationName:@"completeTransaction" object:transactionReceipt];
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction];*/
	//NSString *transactionReceipt = [[NSString alloc] initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding];
	NSLog(@"Transaction　complete===>>>>>>>>>>>");
	//[[NSNotificationCenter defaultCenter]  postNotificationName:@"completeTransaction" object:transaction];
	NSDictionary *tempDict = [NSDictionary dictionaryWithObject:jsonObjectString forKey:@"receipt-data"];
	NSString *josnValue = [tempDict JSONRepresentation];
//	NSLog(@"-------->%@", josnValue);
//	NSURL *sandboxStoreURL = [[NSURL alloc] initWithString: @"https://sandbox.itunes.apple.com/verifyReceipt"];
//	NSData *postData = [NSData dataWithBytes:[josnValue UTF8String] length:[josnValue length]];
//	NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:sandboxStoreURL];
//	[connectionRequest setHTTPMethod:@"POST"];
//	[connectionRequest setTimeoutInterval:120.0];
//	[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
//	[connectionRequest setHTTPBody:postData];
//	

    NSString *urll=[NSString stringWithFormat:@"http://192.168.1.54:9991/pay/paymoney"];
//
//    NSMutableURLRequest *connectionRequest1 = [NSMutableURLRequest requestWithURL:sandboxStoreURL1];
//    	[connectionRequest1 setHTTPMethod:@"POST"];
//    //	[connectionRequest setTimeoutInterval:120.0];
//    //	[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
//    	[connectionRequest1 setHTTPBody:postData];
//        
	
//	NSURLConnection *connection = [[NSURLConnection alloc]
//																 initWithRequest:connectionRequest
//																 delegate:self];
//	[connection release];
    
    
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urll]];
    [request setPostValue:josnValue forKey:@"receipt"];
    [request startSynchronous];
    
    NSString *resultString = [request responseString];
    NSLog(@">>>>>>>>>==%@",resultString);
//    if (resultString!=nil) {
        [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
//    }
}
- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length {
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t *output = (uint8_t *)data.mutableBytes;
    
    for (NSInteger i = 0; i < length; i += 3) {
        NSInteger value = 0;
        for (NSInteger j = i; j < (i + 3); j++) {
            value <<= 8;
            
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        
        NSInteger index = (i / 3) * 4;
        output[index + 0] =                    table[(value >> 18) & 0x3F];
        output[index + 1] =                    table[(value >> 12) & 0x3F];
        output[index + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[index + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }
    
    return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
    NSLog(@"failedTransaction");
	[[NSNotificationCenter defaultCenter] postNotificationName:@"faliedTransaction" object:nil];
	[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

-(void) paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction{
    NSLog(@"paymentQueueRestoreCompletedTransactionsFinished");

}

-(void) paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
    NSLog(@"paymentQueue");

}


#pragma mark connection delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	NSLog(@"====>>>>>%@",  [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
	//[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	switch([(NSHTTPURLResponse *)response statusCode]) {
		case 200:
		case 206:
			break;
		case 304:
	
			break;
		case 400:

			break;
			
			
		case 404:
		break;
		case 416:
			break;
		case 403:
			break;
		case 401:
		case 500:
			break;
		default:
			break;
	}	
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	

}

@end
